package com.gy.controller.user;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "验证码相关接口")
@CrossOrigin
@Slf4j
public class CaptchaController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/captcha")
    @ApiOperation("生成验证码")
    public void getCaptcha(HttpServletResponse response) throws IOException {
        // 生成UUID
        String uuid = UUID.randomUUID().toString();

        // 生成验证码
        String captchaText = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(captchaText);

        // 存入 Redis，有效期5分钟
        String redisKey = "CAPTCHA:" + uuid;
        stringRedisTemplate.opsForValue().set(redisKey, captchaText, 5, TimeUnit.MINUTES);

        // 将图片转换为 Base64 字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] imageBytes = baos.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        // 设置响应头，返回JSON数据
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 生成响应 JSON
        String jsonResponse = String.format("{\"uuid\":\"%s\", \"image\":\"data:image/png;base64,%s\"}", uuid, base64Image);
        response.getWriter().write(jsonResponse);
    }


}
